package com.studentgrowth.controller.recommend;

import com.studentgrowth.model.UserCourseAction;
import com.studentgrowth.model.course.Course;
import com.studentgrowth.repository.UserCourseActionRepository;
import com.studentgrowth.repository.CourseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/recommend")
public class RecommendController {

    @Autowired
    private UserCourseActionRepository userCourseActionRepository;

    @Autowired
    private CourseRepository courseRepository;

    // 记录用户行为
    @PostMapping("/action")
    public Map<String, Object> recordAction(@RequestBody UserCourseAction action) {
        Map<String, Object> result = new HashMap<>();
        try {
            userCourseActionRepository.insert(action);
            result.put("code", 200);
            result.put("message", "ok");
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("message", "error: " + e.getMessage());
        }
        return result;
    }

    // 协同过滤推荐
    @GetMapping("/personal-courses")
    public List<Map<String, Object>> recommendCourses(@RequestParam Integer userId, HttpServletRequest request) {
        try {
            String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
            // 1. 当前用户学过的课程
            List<UserCourseAction> myActions = userCourseActionRepository
                    .selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserCourseAction>()
                            .eq("user_id", userId));
            Set<Integer> myCourseIds = myActions.stream().map(UserCourseAction::getCourseId).collect(Collectors.toSet());

            List<Course> courses;
            if (myCourseIds.isEmpty()) {
                // 没有行为时返回推荐课程
                courses = courseRepository.findRecommendCourses();
            } else {
                // 2. 找到也学过这些课程的其他用户
                List<UserCourseAction> similarActions = userCourseActionRepository
                        .selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserCourseAction>()
                                .in("course_id", myCourseIds)
                                .ne("user_id", userId));
                Set<Integer> similarUserIds = similarActions.stream().map(UserCourseAction::getUserId).collect(Collectors.toSet());

                if (similarUserIds.isEmpty()) {
                    courses = courseRepository.findRecommendCourses();
                } else {
                    // 3. 推荐这些用户学过但当前用户没学过的课程，按出现次数排序
                    List<UserCourseAction> recommendActions = userCourseActionRepository
                            .selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<UserCourseAction>()
                                    .in("user_id", similarUserIds)
                                    .notIn("course_id", myCourseIds));
                    Map<Integer, Long> courseCount = recommendActions.stream()
                            .collect(Collectors.groupingBy(UserCourseAction::getCourseId, Collectors.counting()));

                    // 按出现次数排序，取前6个
                    List<Integer> recommendCourseIds = courseCount.entrySet().stream()
                            .sorted((a, b) -> Long.compare(b.getValue(), a.getValue()))
                            .limit(6)
                            .map(Map.Entry::getKey)
                            .collect(Collectors.toList());

                    if (recommendCourseIds.isEmpty()) {
                        courses = courseRepository.findRecommendCourses();
                    } else {
                        courses = courseRepository.selectBatchIds(recommendCourseIds);
                    }
                }
            }
            // 拼接baseUrl，组装返回字段
            List<Map<String, Object>> result = new ArrayList<>();
            for (Course c : courses) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", c.getId());
                map.put("name", c.getName());
                map.put("cover", baseUrl + c.getCover());
                map.put("instructor", c.getInstructor());
                map.put("description", c.getDescription());
                result.add(map);
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> error = new HashMap<>();
            error.put("id", -1);
            error.put("name", "error: " + e.getMessage());
            error.put("cover", "");
            error.put("instructor", "");
            error.put("description", "");
            return Arrays.asList(error);
        }
    }
} 